// lib/login_register_page.dart

import 'package:flutter/material.dart';
import 'my_home_page.dart';

class LoginRegisterPage extends StatefulWidget {
  const LoginRegisterPage({super.key});

  @override
  State<LoginRegisterPage> createState() => _LoginRegisterPageState();
}

class _LoginRegisterPageState extends State<LoginRegisterPage> {
  bool _isLoginMode = true;
  final _formKey = GlobalKey<FormState>();
  String _username = ''; 
  String _password = '';
  String? _confirmPassword;

  Map<String, String> _mockUsers = { 
    'abc': '123', 
  };

  void toggleFormMode() {
    setState(() {
      _isLoginMode = !_isLoginMode;
    });
  }

  void handleLoginOrRegister() {
    if (_formKey.currentState != null && _formKey.currentState!.validate()) {
      _formKey.currentState!.save();

      if (_isLoginMode) {
        if (!checkIfAccountExists(_username)) { // 改为 username
          // 账号不存在，提示用户注册
          showAlertDialog(context, 'Account Not Found', 'Would you like to register?', toggleFormMode);
        } else {
          navigateToHomeScreen();
        }
      } else {
        if (_password != _confirmPassword!) {
          showAlertDialog(context, 'Error', 'Passwords do not match.', () {});
        } else {
          showAlertDialog(context, 'Success', 'Registration successful!', navigateToLoginScreen);
        }
      }
    }
  }

  bool checkIfAccountExists(String username) { // 改为 username
    // 检查模拟数据中是否存在该用户名
    if (_mockUsers.containsKey(username)) {
      return true;
    }

    return false;
  }

  void navigateToHomeScreen() {
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (context) => const MyHomePage(title: 'Home')),
    );
  }

  void navigateToLoginScreen() {
    setState(() {
      _isLoginMode = true;
    });
  }

  void showAlertDialog(BuildContext context, String title, String content, VoidCallback? onOkPressed) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: Text(content),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              onOkPressed?.call();
            },
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_isLoginMode ? 'Login' : 'Register'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextFormField(
                decoration: const InputDecoration(labelText: 'Username'), // 改为 Username
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your username';
                  }
                  return null;
                },
                onSaved: (value) {
                  _username = value!; // 改为 username
                },
              ),
              TextFormField(
                decoration: const InputDecoration(labelText: 'Password'),
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return 'Please enter your password';
                  }
                  return null;
                },
                onSaved: (value) {
                  _password = value!;
                },
              ),
              if (!_isLoginMode)
                TextFormField(
                  decoration: const InputDecoration(labelText: 'Confirm Password'),
                  obscureText: true,
                  validator: (value) {
                    if (value == null || value.isEmpty) {
                      return 'Please confirm your password';
                    }
                    return null;
                  },
                  onSaved: (value) {
                    _confirmPassword = value!;
                  },
                ),
              ElevatedButton(
                onPressed: () {
                  handleLoginOrRegister();
                },
                child: Text(_isLoginMode ? 'Login' : 'Register'),
              ),
              const SizedBox(height: 16),
              TextButton(
                onPressed: toggleFormMode,
                child: Text(_isLoginMode ? 'New here? Register' : 'Already have an account? Login'),
              ),
            ],
          ),
        ),
      ),
    );
  }
}